package com.henz4help.app;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.henz4help.app.base.BaseActivity;
import com.henz4help.app.common.Util;
import com.henz4help.app.db.domain.PersonalData;


public class SettingsActivity extends BaseActivity{
	
	private TextView vTxtDOB;
	//private TextView vTxtRegId;
	private ImageView vPhotoView;
	private ImageView vBackImg;
	
	private PersonalData mPersonalData;
	
	private boolean dataExistFlag = false;
	
	protected int[] inputTxtIds = {
		  R.id.iTxtFName
		, R.id.iTxtMName
		, R.id.iTxtLName
		, R.id.iTxtAddr1
		, R.id.iTxtAddr2
		, R.id.iTxtCity
		, R.id.iTxtInsuComp
		, R.id.iTxtInsuNo
		, R.id.iTxtEmail
	};
	int[][] inputSpinnerIds = {
		  { R.id.iSpnGender, R.array.userGenderList }
		, { R.id.iSpnState , R.array.userStateList }
	};
	
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings_activity);
		mPersonalData = mDatabaseHelper.retrievePersonalData();
		if(mPersonalData == null) {
			mPersonalData = new PersonalData();
		}else{
			dataExistFlag = true;
		}
		
		mPersonalData.latitude = MainActivity.latitude;
		mPersonalData.longitude = MainActivity.longitude;
		
		setRegid();
		setComponent();
		displayUserData();
		skipProfieUpdateFlag = false;
		
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}
	
	private void displayUserData(){
		EditText editTxt;
		Spinner spinner;
		SpinnerAdapter adpt = null;
		Object item = null;
		
		vTxtDOB.setText(
				  mPersonalData.birthMonth
				+ "/" + mPersonalData.birthDay
				+ "/" + mPersonalData.birthYear
			);
		//vTxtRegId.setText(mPersonalData.regId);
		Util.Log("displayUserData mPersonalData.email[" + mPersonalData.email + "]");
		
		String inputValue = "";
		for(int inputId:inputTxtIds){
			editTxt = (EditText)findViewById(inputId);
			inputValue = "";
			switch (inputId) {
				case R.id.iTxtFName:
					inputValue = mPersonalData.firstName;
				break;
				case R.id.iTxtMName:
					inputValue = mPersonalData.middleInitial;
				break;
				case R.id.iTxtLName:
					inputValue = mPersonalData.lastName;
				break;
				case R.id.iTxtAddr1:
					inputValue = mPersonalData.address;
				break;
				case R.id.iTxtAddr2:
					inputValue = mPersonalData.street;
				break;
				case R.id.iTxtCity:
					inputValue = mPersonalData.city;
				break;
				case R.id.iTxtInsuComp:
					inputValue = mPersonalData.insurance;
				break;
				case R.id.iTxtInsuNo:
					inputValue = mPersonalData.insuranceAccountNo;
				break;
				case R.id.iTxtEmail:
					inputValue = mPersonalData.email;
				break;
				/*
				case R.id.vTxtRegId:
					inputValue = mPersonalData.insuranceAccountNo;
				break;
				*/
				default:
				break;
			}
			editTxt.setText(inputValue);
		}
		for(int[] spinnerId:inputSpinnerIds){
			spinner = (Spinner) findViewById(spinnerId[ 0 ]);
			switch (spinnerId[ 0 ]) {
				case R.id.iSpnGender:
					inputValue = mPersonalData.gender;
				break;
				case R.id.iSpnState:
					inputValue = mPersonalData.state;
				break;
				default:
				break;
			}
			if(inputValue != null){
				adpt = spinner.getAdapter();
				for( int i = 0; i < adpt.getCount(); i ++ ){
					item = adpt.getItem(i);
					if(inputValue.equals(item)){
						spinner.setSelection(i);
					}
				}
			}
		}
		
		//Uri profileUri = Uri.parse("content://com.google.android.gallery3d.provider/picasa/item/5788911720789765266");
		Util.Log("mPersonalData.uriString[" + mPersonalData.uriString + "]");
		if(mPersonalData.uriString != null && !"".equals(mPersonalData.uriString)){
			Uri profileUri = Uri.parse( mPersonalData.uriString );
			vPhotoView.setImageURI(profileUri);
		}
		
		
	}
	
	protected boolean skipProfieUpdateFlag = true;
	private void updatePersonalData(){
		Util.Log("updatePersonalData[" + skipProfieUpdateFlag + "]");
		if(!skipProfieUpdateFlag){
			Util.Log("updatePersonalData[" + mPersonalData + "]");
			Util.Log("updatePersonalData[" + mPersonalData.email + "]");
			if(dataExistFlag){
				mDatabaseHelper.updatePersonalData(mPersonalData);
			}else{
				mDatabaseHelper.insertPersonalData(mPersonalData);
				dataExistFlag = true;
			}
		}
	}
	
	private void setDOB( int year, int month, int day ){
		mPersonalData.birthYear = year;
		mPersonalData.birthMonth = month;
		mPersonalData.birthDay = day;
		
		vTxtDOB.setText(
			  mPersonalData.birthMonth
			+ "/" + mPersonalData.birthDay
			+ "/" + mPersonalData.birthYear
		);
		updatePersonalData();
	}
	
	
	private View.OnTouchListener mDboListener = new View.OnTouchListener() {		
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			datePickerDlg();
			return true;
		}
	};
	
	private static final int SELECT_PROFILE = 1;
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (resultCode == Activity.RESULT_OK) {
	        if (requestCode == SELECT_PROFILE) {
	        	Util.Log("SELECT_PROFILE==========");
				Uri profileUri = data.getData();
				Util.Log("SELECT_PROFILE[" 
					+ profileUri 
					+ "][" 
					+ profileUri.getPath() 
					+ "][" 
					+ profileUri.toString() 
					+ "]"
				);
				vPhotoView.setImageURI(profileUri);
				mPersonalData.uriString = profileUri.toString();
				Util.Log("onActivityResult[" + mPersonalData.uriString + "]");
				updatePersonalData();
				
	        }

	    }

	}	
	private View.OnTouchListener imgPhotoListener = new View.OnTouchListener() {		
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			Util.Log("imgPhotoListener[" + v.getId() + "][" + event.getAction() + "]");
			if( event.getAction() == MotionEvent.ACTION_DOWN ){
				Intent i = new Intent(
						Intent.ACTION_PICK
						, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
						//, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI
				);
				startActivityForResult(i, SELECT_PROFILE);
			}
			return true;
		}
	};
	
	/**

	 *
	 */
	
	protected class SimpleListener{
		protected int editId = 0;
		protected void afterChangedValue( String editValue ){
			switch (this.editId) {
				/**
				 * Editable Text Start
				 */
				case R.id.iTxtFName:
					mPersonalData.firstName = editValue;
				break;
				case R.id.iTxtMName:
					mPersonalData.middleInitial = editValue;
				break;
				case R.id.iTxtLName:
					mPersonalData.lastName = editValue;
				break;
				case R.id.iTxtAddr1:
					mPersonalData.address = editValue;
				break;
				case R.id.iTxtAddr2:
					mPersonalData.street = editValue;
				break;
				case R.id.iTxtCity:
					mPersonalData.city = editValue;
				break;
				case R.id.iTxtInsuComp:
					mPersonalData.insurance = editValue;
				break;
				case R.id.iTxtInsuNo:
					mPersonalData.insuranceAccountNo = editValue;
				break;
				case R.id.iTxtEmail:
					mPersonalData.email = editValue;
				break;
				/**
				 * Editable Text end
				 */
				
				/**
				 * Editable Text Start
				 */
				case R.id.iSpnGender:
					mPersonalData.gender = editValue;
				break;
				case R.id.iSpnState:
					mPersonalData.state = editValue;
				break;
				default:
				break;
				/**
				 * Editable Text End
				 */
			}
			updatePersonalData();
		}
	}
	
	protected class SimpleTextWatcher extends SimpleListener implements TextWatcher{
		
		protected EditText editObj = null;
		
		public SimpleTextWatcher( int inputId, EditText editTxt ){
			this.editId = inputId;
			this.editObj = editTxt;
		}
		
		public void afterChanged() {
			String editValue = editObj.getText().toString();
			afterChangedValue(editValue);
		}
		
        @Override
        public void afterTextChanged(Editable s) {
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        	afterChanged();
        }
        
	}
	
	protected class SimpleSpinnerListener extends SimpleListener implements AdapterView.OnItemSelectedListener{

		
		protected Spinner editObj = null;
		
		public SimpleSpinnerListener( int spinnerId, Spinner spinner ){
			this.editId = spinnerId;
			this.editObj = spinner;
		}
		
		protected void afterChanged(){
			String editValue = editObj.getSelectedItem().toString();
			afterChangedValue(editValue);
		}
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			afterChanged();
		}
		@Override
		public void onNothingSelected(AdapterView<?> parent) {
		}
	}
	
	private View.OnTouchListener mBackListener = new View.OnTouchListener() {		
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			onBackPressed();
			return true;
		}
	};
	
	
	
	private void setComponent() {
		
		Spinner spinner = null;
		ArrayAdapter<CharSequence> adapter = null;
		
		vBackImg = (ImageView)findViewById(R.id.imvBackInSettings);
		vBackImg.setOnTouchListener(mBackListener);
		
		
		vTxtDOB = (TextView)findViewById(R.id.vTxtDOB);
		vTxtDOB.setOnTouchListener(mDboListener);
		
		//vTxtRegId = (TextView)findViewById(R.id.vTxtRegId);
		
		vPhotoView = (ImageView)findViewById(R.id.imvPhotoInSettings);
		vPhotoView.setOnTouchListener(imgPhotoListener);
		
		EditText editTxt;
		for(int inputId:inputTxtIds){
			editTxt = (EditText)findViewById(inputId);
			editTxt.addTextChangedListener(new SimpleTextWatcher(inputId, editTxt));
		}
		
		for(int[] spinnerId:inputSpinnerIds){
			spinner = (Spinner) findViewById(spinnerId[ 0 ]);
			adapter = ArrayAdapter.createFromResource(this,
					spinnerId[ 1 ], android.R.layout.simple_spinner_item);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinner.setAdapter(adapter);
			
			spinner.setOnItemSelectedListener(new SimpleSpinnerListener(spinnerId[ 0 ], spinner));
		}
	}
	
	private DatePickerDialog dobDialogue = null;
	
	private void datePickerDlg() {
		
		if(dobDialogue == null){
			int year;
			int month;
			int day;
			
			year = mPersonalData.birthYear;
			month = mPersonalData.birthMonth - 1;
			day = mPersonalData.birthDay;
			
			dobDialogue = new DatePickerDialog(
					  this
					, new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int month, int day) { } }
					, year
					, month
					, day
				);
			
			dobDialogue.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(R.string.complete), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					DatePickerDialog dpDialogue = null;
					DatePicker picker = null;
					
					dpDialogue = (DatePickerDialog)dialog;
					picker = dpDialogue.getDatePicker();
					
					setDOB(
						  picker.getYear()
						, picker.getMonth() + 1
						, picker.getDayOfMonth()
					);
					
				}
			});
			
			dobDialogue.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
		}
		
		dobDialogue.show();
		
	}
	
	
	/**
	 * GCM Start
	 */
	private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
	public static final String EXTRA_MESSAGE = "message";
	public static final String PROPERTY_REG_ID = "registration_id";
	private static final String PROPERTY_APP_VERSION = "appVersion";
	protected String SENDER_ID = "henzmobile";
	private GoogleCloudMessaging gcm =null;
	private String regid = null;
	private Context context= null;	
	
	protected void setRegid() {
		if (checkPlayServices()) {
			gcm = GoogleCloudMessaging.getInstance(this);
			regid = getRegistrationId(context);

			if (regid.isEmpty()) {
				registerInBackground();
			} else {
				Util.Log("No valid Google Play Services APK found.");
			}
			mPersonalData.regId = regid;
			updatePersonalData();
		}
		
		
	}
	
	private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
            	Util.Log("This device is not supported - Google Play Services.");
                //finish();
            }
            return false;
        }
        return true;
	}
	
	private String getRegistrationId(Context context) 
	{
	   final SharedPreferences prefs = getGCMPreferences(context);
	   String registrationId = prefs.getString(PROPERTY_REG_ID, "");
	   if (registrationId.isEmpty()) {
		   Util.Log("Registration ID not found.");
	       return "";
	   }
	   int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
	   int currentVersion = getAppVersion(context);
	   if (registeredVersion != currentVersion) {
		   Util.Log("App version changed.");
	        return "";
	    }
	    return registrationId;
	}	
	
	private SharedPreferences getGCMPreferences(Context context) 
	{
	    return getSharedPreferences(MainActivity.class.getSimpleName(),
	                Context.MODE_PRIVATE);
	}

	private static int getAppVersion(Context context) 
	{
	     try 
	     {
	         PackageInfo packageInfo = context.getPackageManager()
	                    .getPackageInfo(context.getPackageName(), 0);
	            return packageInfo.versionCode;
	      } 
	      catch (Exception e) 
	      {
	            throw new RuntimeException("Could not get package name: " + e);
	      }
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void registerInBackground() {
		(new AsyncTask() {
			@Override
			protected Object doInBackground(Object... params) {
				{
					String msg = "";
					try {
						if (gcm == null) {
							gcm = GoogleCloudMessaging.getInstance(context);
						}
						regid = gcm.register(SENDER_ID);
						Util.Log("########################################");
						Util.Log("Current Device's Registration ID is: " + msg);
					} catch (Exception ex) {
						msg = "Error :" + ex.getMessage();
					}
					return null;
				}
			}

			protected void onPostExecute(Object result) {

			};
		}).execute(null, null, null);
	}

	/**
	 * GCM End
	 */
	
	
}
